package date;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class Music {
private Clip clip;
    public Music(String resourcePath) {
        // 使用 ClassLoader 获取音频资源的输入流
        var audioStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
        if (audioStream == null) {
            System.err.println("未找到音频资源: " + resourcePath);
            return;
        }
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioStream);
            clip = AudioSystem.getClip();
            clip.open(audioInputStream);
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    //开始播放
    public void playLoop() {
        if (clip != null) {
            clip.loop(Clip.LOOP_CONTINUOUSLY);
            clip.start();
        }
    }
    //停止播放
    public void stop() {
        if (clip != null && clip.isRunning()) {
            clip.stop();
            clip.close();
        }
    }
}